#coding:utf-8
from django.shortcuts import render,HttpResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q #Q()完成并集
from django.views.generic.base import View
from .qm_interface_test.qm_interface import *
from .qm_interface_test.log import *
import uuid
import time
import json


import sys
reload(sys)
sys.setdefaultencoding('utf-8')

logger=logger("Main")


class Inter_get_result(View):
    def get(self, request):
        return render(request, "interface.html",{})

            
# Create your views here.
class Interface_api(View):

    def get(self, request):
        # return render(request, "interface.html",{})
        print "get api"
        return HttpResponse('{\
                "code":"S001",\
                "flag":"failure",\
                "message":"parse params error"\
        }')

    def post(self, request):
        post_method = request.POST.get("postmethod", "")
        print "post_method",post_method
        post_url = request.POST.get("url", "")
        post_content = request.POST.get("content", "")
        post_type = request.POST.get("posttype", "")
        inter_mothd = request.POST.get("inter_mothd","")
        time_str = time.strftime("%Y-%m-%d %H:%M:%S")
        time_rod = str(uuid.uuid1())[10:25].replace("-","")

        result = {}
        if post_method == "POST_METHOD":
            print "POST_METHOD"
            if post_content and post_url:
                if post_type == "qm_inter":
                #奇门接口
                    try: 
                        logger.info("format conent.")
                        other_content=str(post_content).format(timestr=time_str, time_rod=time_rod)
                        
                    except KeyError as e:
                        #解决format无法解析<a>[{"k":"v"}]<a/>问题
                        logger.info("format content error %s." % e)
                        logger.info("replace conent")
                        other_content = (str(post_content).replace("{timestr}", time_str)).replace("{time_rod}", time_rod)

                    except Exception as e:
                        logger.error("handle conent error %s " % e)
                        result["res"] = "error1: "+ str(e) + " unable to parse"
                        return HttpResponse(json.dumps(result))     
                        
                    try:
                        fh = u"发货 fh fhd b2c 发货单创建 订单创建"
                        ck = u"dbck ptck ck b2bck tgck tg  退供出库单  调拨出库单 "
                        rk = u"cgrk dbrk rk xtrk cgrkd dbrk 创建采购入库单创建 创建调拨入库创建 "
                        sp = u"更新商品 add update gxsp zjsp 增加商品"
                        qx = u"取消订单qxddcancel"
                        _inter_mothd = str(inter_mothd).lower().strip()

                        """过滤单据类型，根据类型调用不同的mothod方法"""
                        if _inter_mothd == "":  
                            #order type 空判断
                            # print "0"
                            result["res"] = "order type is null. please check your input."
                            return HttpResponse(json.dumps(result))

                        if _inter_mothd in fh:
                            #发货单创建
                            logger.info("create b2c order")
                            result = Xml2Json(qm_interface("deliveryorder.create", other_content=str(other_content))).result
                            return HttpResponse(json.dumps(result))

                        elif _inter_mothd in ck:
                            #出库单创建
                            logger.info("create ck order")
                            result = Xml2Json(qm_interface("stockout.create", other_content=str(other_content))).result
                            return HttpResponse(json.dumps(result))

                        elif _inter_mothd in rk:
                            #入库单创建 entryorder.create
                            logger.info("create rk order")
                            result = Xml2Json(qm_interface("entryorder.create", other_content=str(other_content))).result
                            return HttpResponse(json.dumps(result))

                        elif _inter_mothd in sp:
                            logger.info("add or update sp message")
                            #商品同步singleitem.synchronize    "<outcode>{0}</outcode>".format(time_rod)
                            qm_sp_result = qm_interface("singleitem.synchronize", other_content=str(other_content))
                            result["outcode"] = str(time_rod)
                            result["response"] = Xml2Json(qm_sp_result).result
                            return HttpResponse(json.dumps(result))

                        elif _inter_mothd in qx:
                            #取消订单
                            logger.info("cancel order")
                            result = Xml2Json(qm_interface("order.cancel", other_content=str(other_content))).result
                            return HttpResponse(json.dumps(result))

                        else:
                            #若查询不到的判断
                            # print "6"
                            logger.info("has not found")
                            result["response"] = "order type " +str(inter_mothd) + " have not found."
                            return HttpResponse(json.dumps(result))

                    except Exception as e:
                        logger.error("create order failed.")
                        result["res"] = str(e)
                        return HttpResponse(json.dumps(result))
   
                elif post_type == "com_inter":
                #兼容普通post接口，不够强大加密签名方法没做到很多支持。后期有时间情况下还要优化一下。
                    try:
                        result["res"] = com_post_req(post_url, post_content)
                    except Exception as e:
                        result["res"] = str(e)
                    return HttpResponse(json.dumps(result))

            elif post_content and post_type == "":
                #解析报文
                try:
                    test = str(post_content).format(timestr=time_str, time_rod=time_rod)
                    result["res"] = test
                except Exception as e:
                    result["res"] = str(e) + " unable to parse"
                return HttpResponse(json.dumps(result))
            else:
                result["res"] = "post_content or post_url is null"
                return HttpResponse(json.dumps(result))

        elif post_method == "GET_METHOD":
            #GET 兼容普通接口
            print "GET_METHOD"
            if post_content and post_url:
                print "get111111"
                try:
                    print "get111111-try"
                    result["res"] = common_get_req(post_url, payload=post_content)
                except  Exception as e:
                    print "get111111-except"
                    result["res"] = "unable to parse. please check your input"
                return HttpResponse(json.dumps(result))

            elif post_url:
                print "11111111111"
                result["res"] = common_get_req(post_url)
                return HttpResponse(json.dumps(result))

            elif post_content:
            #解析报文
                try:
                    result["res"] = str(post_content).format(timestr=time_str, time_rod=time_rod)            
                except Exception as e:
                    result["res"] = str(e) + " unable to parse"
                return HttpResponse(json.dumps(result))
            else:
                result["res"] = "url is null"
                return HttpResponse(json.dumps(result))

        elif post_method == "OPTIONS_METHOD":
            #OPTIONS 接口
            print "OPTIONS_METHOD"
            if post_url == "":
                result["rec"] = "url is null. please check your input."
                return HttpResponse(json.dumps(result))
            try:
                result["res"] = str(com_options_req(post_url))
            except Exception as e:
                result["res"] = str(e)
            return HttpResponse(json.dumps(result))

        elif post_content:
            #解析报文
            print "post conttent-======"
            try:
                test = str(post_content).format(timestr=time_str, time_rod=time_rod)
                result["res"] = test
            except Exception as e:
                result["res"] = str(e) + " unable to parse"
            return HttpResponse(json.dumps(result))

        else:
            result['rec']='parse params error'
            print "get api"
            return HttpResponse("json.dumps(result)")

        

class Url_dec_enc(View):
    #URL编解码，+时还没有办法解码成空格。需优化
    def get(self, request):
        return render(request, "url_encode.html",{})

    def post(self, request):
        pass
        url_encode_cont = request.POST.get("url_enc_content", "")

        if url_encode_cont:
            pass
        else:
            pass


if __name__ == '__main__':
    logger.info("Table created successfully")